package ClientCommands;

import Annotations.IsClientCommand;
import Commands.ClientCommandBase;
import DomainLayer.CommentaryEntity;
import DomainLayer.ICommentable;
import DomainLayer.UserEntity;
import Helpers.ApplicationLogger;
import org.json.simple.JSONObject;

import java.io.IOException;

@IsClientCommand
public class AddNewCommentary extends ClientCommandBase<Boolean>{

    private int objectId;
    private String text;
    private int userId;
    private String objectType;

    private void setObjectId(int id) {
        objectId = id;
    }

    private void setObjectId(String str) {
        try {
            objectId = Integer.parseInt(str);
        }
        catch (NumberFormatException e) {
            e.printStackTrace();
        }
    }

    private void setText(String str) {
        text = str;
    }

    private void setUserId(int id) {
        userId = id;
    }

    private void setUserId(String str) {
        try {
            userId = Integer.parseInt(str);
        }
        catch (NumberFormatException e) {
            e.printStackTrace();
        }
    }

    private void setObjectType(String str) {
        objectType = str;
    }

    public void FillFromJSON(JSONObject jObj) {
		super.FillFromJSON(jObj);
		setObjectId((String)jObj.get("objectId")); //id of the object we want to add commentary
		setText((String)jObj.get("text"));  // text of the commentary
        setUserId((String)jObj.get("userId"));   // id of the user who want to add commentary
        setObjectType((String)jObj.get("objectType")); // type of the object we want to add commentary
	}


    protected void ExecuteInternal() throws IOException{
        try {
        	Boolean result = false;
            ICommentable commentableEntity = ServiceLayer.ServiceFacade.getInstance().GetICommentableObjectByIdAndType(objectId, objectType);
            if (commentableEntity != null) {
                commentableEntity.createCommentary(text, (UserEntity) ServiceLayer.ServiceFacade.getInstance().GetUserById(userId));
                result = ServiceLayer.ServiceFacade.getInstance().AddCommentary(commentableEntity);
            }
            setResult(result);
        }
        catch (Throwable e) {
			ApplicationLogger.getInstance().LOG.error(e.getMessage());
		}
        
    }
}
